const koa = require('koa');
const proxy = require('koa-better-http-proxy');
const colors = require('colors');

const { getToken } = require('./token');

const TOKEN_KEY1 = 'Authorization';
const TOKEN_KEY2 = 'Cloud-Authorization';

async function startServer(options) {
  const app = new koa();

  getToken(options).then(res => {
    app.use(
      proxy(options.target, {
        proxyReqOptDecorator: function (proxyReqOpts, ctx) {
          return new Promise(function (resolve, reject) {
            proxyReqOpts.headers[TOKEN_KEY1] = res[0];
            if (res[1]) {
              proxyReqOpts.headers[TOKEN_KEY2] = res[1];
            }
            resolve(proxyReqOpts);
          });
        },
      }),
    );
    app.listen(options.port, () => {
      console.log(`${colors.blue(options.name)} server start in port ${colors.yellow(options.port)}`);
    });
  });
}

module.exports = {
  startServer,
};
